<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">状态：{{ data.form.docStatus }}</h3>
            <h3 style="display: inline">审核：{{ data.form.approved }}</h3>
          </a-space>
        </a-col>

        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()"> 返 回</a-button>
              <a-button @click="add()"> 新 增</a-button>
              <a-button @click="save()" :disabled="data.form.docStatus === 'C' || !data.form.edit"> 保 存</a-button>
              <a-button @click="edit()" :disabled="data.form.docStatus === 'C' || data.form.edit || data.form.docStatus === 'L'"> 编 辑</a-button>
              <a-button @click="del()" :disabled="data.form.edit || data.form.docStatus === 'L' || data.form.approved"> 删 除</a-button>
              <a-button @click="approved()" :disabled="data.form.edit">查看审核</a-button>
              <a-dropdown arrow :disabled="data.form.edit || data.form.docStatus === 'L'">
                <a-button>更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="data.form.docStatus !== 'C'">关闭</a-menu-item>
                    <a-menu-item key="b" v-if="!(data.form.docStatus !== 'C')">打开</a-menu-item>
                    <a-menu-item key="c">上传审核</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>
      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="文件名称" name="name">
              <a-input v-if="data.form.edit" v-model:value="data.form.name" />
              <span v-else>{{ data.form.name }}</span>
            </a-form-item>
            <a-form-item label="文件类型" name="typeId">
              <FiletypeTreeSelect v-if="data.form.edit" key="docEntry" v-model:value="data.form.typeId" @change="changeHandle"></FiletypeTreeSelect>
              <span v-else>{{ data.form.typeName }}</span>
            </a-form-item>
            <a-form-item label="公开文件" name="docPrivate">
              <a-radio-group v-if="data.form.edit" v-model:value="data.form.docPrivate">
                <a-radio value="A">公开</a-radio>
                <a-radio value="B">私密</a-radio>
              </a-radio-group>
              <span v-else>
                <a-tag v-if="data.form.docPrivate === 'A'" color="#87d068">公开 </a-tag>
                <a-tag v-if="data.form.docPrivate === 'B'" color="#f50">私密 </a-tag>
              </span>
            </a-form-item>

            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>

          <a-col :span="8"></a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="版本">
            <a-row>
              <a-button-group>
                <a-button :disabled="data.form.docStatus === 'L'" @click="lineaImportFile" type="link">
                  <template #icon>
                    <ImportOutlined />
                  </template>
                  上传文件
                </a-button>
              </a-button-group>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-table
                  row-key="lineNum"
                  :columns="columnsa"
                  :data-source="data.form.lista"
                  :scroll="{ x: 1920, y: 500 }"
                  :pagination="{
                    showSizeChanger: true,
                    showQuickJumper: true,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100', '200'],
                  }"
                >
                  <template #bodyCell="{ text, record, column, index }">
                    <template v-if="column.dataIndex === 'docSize'">
                      <span> {{ getFileSize(text) }}</span>
                    </template>
                    <template v-if="column.dataIndex === 'approve'">
                      <span> {{ text ? '已审核' : '未审核' }}</span>
                    </template>
                    <template v-if="column.dataIndex === 'action'">
                      <a-button v-if="index === 0 && record.approve && record.printApprov" @click="print(record)" type="link">
                        <template #icon>
                          <PrinterOutlined />
                        </template>
                        打印
                      </a-button>
                      <a-button
                        v-if="index === 0 && record.approve && !record.printApprov && data.form.docStatus !== 'L'"
                        @click="PrintApply(record)"
                        type="link"
                        >打印申请
                      </a-button>
                      <a-button
                        v-if="index === 0 && record.approve && !record.printApprov && data.form.docStatus !== 'L'"
                        @click="recycleApply(record)"
                        type="link"
                        >回收申请
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="3" tab="打印">
            <a-table
              row-key="lineNum"
              :header-height="30"
              :columns="columnsaa"
              :data-source="data.form.listaa"
              :scroll="{ x: 1920, y: 500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'approved'">
                  <span> {{ text ? '已审核' : '未审核' }}</span>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button @click="linebDel(record)" type="link"> 移除</a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="4" tab="回收">
            <a-table
              row-key="lineNum"
              :header-height="30"
              :columns="columnsab"
              :data-source="data.form.listab"
              :scroll="{ x: 1920, y: 500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button @click="linebDel(record)" type="link"> 移除</a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="人员">
            <a-button-group>
              <a-button :disabled="data.form.docStatus === 'L'" @click="addRoleEmployee" type="link">
                <template #icon>
                  <ImportOutlined />
                </template>
                选择开通
              </a-button>
            </a-button-group>
            <a-table
              row-key="lineNum"
              :header-height="30"
              :columns="columnsb"
              :data-source="data.form.listb"
              :scroll="{ x: 1920, y: 500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button @click="linebDel(record)" type="link"> 移除</a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>

  <a-modal draggable="true" v-model:open="data.uploadModalFlag" title="上传文件" @ok="hideUploadModal">
    <FileUpload
      list-type="text"
      accept=".pdf"
      :maxUploadSize="1"
      buttonText="点击上传文件"
      :defaultFileList="[]"
      :multiple="true"
      :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
      @change="success"
    />
  </a-modal>

  <a-drawer v-model:open="data.drawerFlag" width="100%" destroy-on-close>
    <iframe width="100%" height="100%" :src="`${data.docSrc}#toolbar=0`"></iframe>
  </a-drawer>
  <Approve :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approve>
  <EmployeeTableSelectModal ref="selectEmployeeModal" @selectData="selectData" />

  <a-modal width="800px" v-model:open="data.modalFlag" title="提示" @ok="onFinish">
    <a-form :model="data.forma" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off">
      <a-form-item label="打印份数" name="printNum">
        <a-input-number min="1" v-model:value="data.printNum" addon-after="份"></a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal width="800px" v-model:open="data.modalRecycleFlag" title="提示" @ok="onRecycleFinish">
    <a-form :model="data.forma" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off">
      <a-form-item label="回收份数" name="printNumDra">
        <a-input-number min="1" v-model:value="data.printNum" addon-after="份"></a-input-number>
      </a-form-item>
      <a-form-item label="回收资料" name="printNumDra">

      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { docmentaApi, docmentApi, docmentaaApi,docmentabApi } from '/@/api/business/file/docment-api.js';
  import FiletypeTreeSelect from '/@/views/business/file/filetypeData/components/filetype-tree-select.vue';
  import { useRouter, useRoute } from 'vue-router';
  import { FILE_FOLDER_TYPE_ENUM } from '/src/constants/support/file-const.js';
  import FileUpload from '/src/components/support/file-upload/index.vue';
  import { columnsa, columnsb, columnsaa, columnsab } from '/@/views/business/file/docmentData/data.js';
  import Approve from '/@/components/business/exam/approve.vue';
  import { approvordApi } from '/@/api/business/erp/approvord-api.js';
  import EmployeeTableSelectModal from '/@/components/system/employee-table-select-modal/index.vue';
  import _ from 'lodash';
  import { SmartLoading } from '/@/components/framework/smart-loading/index.js';

  const route = useRoute();
  const router = useRouter();
  const data = reactive({
    form: {
      docEntry: 0,
      objId: null,
      objName: null,
      absId: '',
      approved: false,
      docStatus: 'O',
      edit: false,
      typeId: '',
      typeName: '',
      docPrivate: 'A',
      lista: [],
      listb: [],
      listaa: [],
      listab: [],
    },
    forma: {},
    radioGroup: null,
    rules: {
      name: [{ required: true, message: '请输入文件名称' }],
      typeId: [{ required: true, message: '请选择文件类型' }],
      docPrivate: [{ required: true, message: '请选择公开状态' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
      user: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
    activeKey: '1',
    uploadModalFlag: false,
    drawerFlag: false,
    modalFlag: false,
    modalRecycleFlag: false,
    docSrc: '',
    chooseLine: null,
    printNum: 1,
  });
  const tableLoading = ref(false);
  const formRef = ref(null);
  const selectEmployeeModal = ref();

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      docmentApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      docmentApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      data.modalFlag = true;
    } else if (key === 'e') {
      data.modalRecycleFlag = true;
      // approvordApi
      //   .add({
      //     docEntry: 0,
      //     approvLineNum: 2,
      //     approvType: 'D',
      //     baseEntry: data.form.docEntry,
      //     tabName: data.form.objName,
      //     docStatus: 'O',
      //     tabId: data.form.objId,
      //     baseVersion: data.form.version,
      //   })
      //   .then((res) => {
      //     queryData();
      //   });
    }
  }

  // 增删改查
  function add() {
    data.form = {};
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/file/docmenta', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          docmentApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.docEntry);
              message.success('修改成功！');
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        } else {
          docmentApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/file/docmenta', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        docmentApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/file/docment' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  async function queryData() {
    tableLoading.value = true;

    await docmentApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
        tableLoading.value = false;
      })
      .catch((error) => {
        tableLoading.value = false;
      });
  }

  function refresh() {
    queryData();
  }

  function back() {
    router.push({ path: '/file/docment' });
  }

  // 审核------------------------------------------------------------------------------------------------

  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.approvedData.title = '24324324';
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  function hideUploadModal(item) {
    data.uploadModalFlag = false;
  }

  function success(item) {
    data.form.lista.push({
      docEntry: data.form.docEntry,
      lineNum: data.form.lista.length + 1,
      lineStatus: 'O',
      title: item[0].fileName,
      docKey: item[0].fileKey,
      docUrl: item[0].fileUrl,
      type: item[0].fileType,
      folder: '文件系统',
      docSize: item[0].fileSize,
    });
    save();
  }

  function changeHandle(item, it) {
    data.form.typeName = it;
  }

  /*---------------------------------------------a--------------------------------------------------------*/

  function onFinish() {
    docmentaaApi
      .add({
        docEntry: data.form.docEntry,
        lineNum: null,
        baseNum: data.chooseLine.lineNum,
        printNum: data.printNum,
      })
      .then((res) => {
        docmentApi
          .update(data.form)
          .then((res) => {
            queryData(data.form.docEntry);
            approvordApi
              .add({
                docEntry: 0,
                approvLineNum: 2,
                approvType: 'C',
                baseEntry: data.form.docEntry,
                tabName: data.form.objName,
                docStatus: 'O',
                tabId: data.form.objId,
              })
              .then((res) => {
                data.modalFlag = false;
                queryData();
              });
          })
          .catch((err) => {
            tableLoading.value = false;
          });
      })
      .catch((err) => {});
  }

  function onRecycleFinish() {
    docmentabApi
        .add({
          docEntry: data.form.docEntry,
          lineNum: null,
          baseNum: data.chooseLine.lineNum,
          printNum: data.printNum,

        })
        .then((res) => {
          docmentApi
              .update(data.form)
              .then((res) => {
                queryData(data.form.docEntry);
                approvordApi
                    .add({
                      docEntry: 0,
                      approvLineNum: 2,
                      approvType: 'D',
                      baseEntry: data.form.docEntry,
                      tabName: data.form.objName,
                      docStatus: 'O',
                      tabId: data.form.objId,
                    })
                    .then((res) => {
                      data.modalFlag = false;
                      queryData();
                    });
              })
              .catch((err) => {
                tableLoading.value = false;
              });
        })
        .catch((err) => {});
  }


  function PrintApply(item) {
    data.modalFlag = true;
    data.chooseLine = item;
  }
  function recycleApply(item) {
    data.modalRecycleFlag = true;
    data.chooseLine = item;
  }

  function lineaview(item) {
    data.drawerFlag = true;
    data.docSrc = item.docUrl;
  }

  function lineaImportFile() {
    if (data.form.lista.length === 0 || data.form.lista[0].printNum === 0) {
      data.uploadModalFlag = true;
    } else {
      Modal.error({
        title: '错误',
        content: `上传新文件前请先将之前打印 【${data.form.lista[0].title}】 的  【${data.form.lista[0].printNum}】 份文件回收！`,
      });
    }
  }

  function getFileSize(size) {
    //把字节转换成正常文件大小
    if (!size) return '';
    let num = 1024.0; //byte
    if (size < num) return size + 'B';
    if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + 'KB'; //kb
    if (size < Math.pow(num, 3)) return (size / Math.pow(num, 2)).toFixed(2) + 'MB'; //M
    if (size < Math.pow(num, 4)) return (size / Math.pow(num, 3)).toFixed(2) + 'G'; //G
    return (size / Math.pow(num, 4)).toFixed(2) + 'T'; //T
  }

  function pagesRendered(pdfApp) {}

  function print(item) {
    /*
     * 更新打印次数和人
     *
     *
     * */

    docmentaApi
      .update(item)
      .then(() => {
        queryData();
        let contractUrl = item.docUrl;
        fetch(contractUrl)
          .then((res) => {
            return res.blob(); //将url地址转化为blob
          })
          .then((res) => {
            var iframe = document.createElement('iframe');
            iframe.style.frameborder = 'no';
            iframe.style.display = 'none';
            iframe.style.pageBreakBefore = 'always';
            iframe.setAttribute('id', `printPdf${item.lineNum}`); //id要是唯一的，不然会获取到上一个PDF文件的内容
            iframe.setAttribute('name', `printPdf${item.lineNum}`);
            iframe.src = window.URL.createObjectURL(res); //创建一个包含指定对象的URL

            document.body.appendChild(iframe);
            doPrint(`printPdf${item.lineNum}`);
            window.URL.revokeObjectURL(iframe.src); //释放url
          });
      })
      .catch((err) => {});
  }

  function doPrint(val) {
    var ordonnance = document.getElementById(val).contentWindow;
    setTimeout(() => {
      ordonnance.print();
    }, 500);
  }

  //--------------------------------------------b-------------------------------------------

  function linebDel(item) {
    data.form.listb.splice(item.lineNum - 1, 1);
    for (let i = item.lineNum - 1; i < data.form.listb.length; i++) {
      data.form.listb[i].lineNum = data.form.listb[i].lineNum - 1;
    }
    save();
  }

  function linebOpen(item) {
    data.visible.user = true;
  }

  function onLinebColse(item) {
    item.forEach((it) => {
      data.form.listb.push({
        docEntry: data.form.docEntry,
        lineNum: data.form.listb.length + 1,
        userId: it.employeeId,
        userName: it.loginName,
      });
    });
    docmentApi
      .update(data.form)
      .then((res) => {
        queryData(data.form.docEntry);
        message.success('修改成功！');
      })
      .catch((err) => {
        queryData(data.form.docEntry);
      });
    data.visible.user = false;
  }

  async function addRoleEmployee() {
    let selectedIdList = data.form.listb.map((e) => e.userId) || [];
    selectEmployeeModal.value.showModal(selectedIdList);
  }

  async function selectData(list) {
    if (_.isEmpty(list)) {
      message.warning('请选择角色人员');
      return;
    }
    SmartLoading.show();
    try {
      list.forEach((it) => {
        data.form.listb.push({
          docEntry: data.form.docEntry,
          lineNum: data.form.listb.length + 1,
          userId: it,
        });
      });
      save();
      message.success('添加成功');
      await queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  onMounted(init);
</script>

<style lang="less">
  .ant-btn {
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
